package pl.edu.agh.broker.server;

import java.io.FileInputStream;
import java.util.Properties;

import org.apache.activemq.broker.BrokerFactory;
import org.apache.activemq.broker.BrokerService;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import pl.edu.agh.broker.mns.client.DefaultResponder;
import pl.edu.agh.broker.mns.server.MultiNameServiceStarter;
import pl.edu.agh.broker.mns.shared.MultiNameService;

public class Main {

	private static final String BROKER_URL = "broker.url";
	private static final String BROKER_ID = "broker.id";
	private static final String MNS_PORT = "mns.port";

	private static final String LOGGER_CONFIG = "src/main/resources/log4j.properties";
	private static final Logger LOGGER = Logger.getLogger(Main.class);
	private static final String PROPERTY_FILE = "conf/broker.properties";

	public static void main(String[] args) {

		// initialize log4j
		PropertyConfigurator.configure(LOGGER_CONFIG);
		LOGGER.info("Starting ActiveMQ broker");

		try {
			// load properties
			Properties properties = new Properties();
			properties.load(new FileInputStream(PROPERTY_FILE));

			// configure and start broker
			BrokerService brokerService = BrokerFactory
					.createBroker("xbean:activemq.xml");
			brokerService.start();

			// register broker in name service
			MultiNameService multiNameService = MultiNameServiceStarter
					.createMultiNameService(Integer.parseInt(properties
							.getProperty(MNS_PORT)));
			multiNameService.add(properties.getProperty(BROKER_ID),
					properties.getProperty(BROKER_URL), new DefaultResponder());
			LOGGER.info("Main Broker started");

			brokerService.waitUntilStopped();

		} catch (Exception e) {
			LOGGER.error("", e);
		}

	}

}
